<?php

namespace Tictactoe;

class Game {

    /**
     * @var array dwuwymiarowa tablica X,Y
     */
    protected $game = array();

    public function __construct($game) {
        $this->setGame($game);
    }

    public function getGame() {
        return $this->game;
    }

    public function setGame($game) {
        $this->game = $game;
    }

    public function getValue($x, $y) {
        if (isset($this->game[$x][$y])) {
            return $this->game[$x][$y];
        }

        return null;
    }

    public function setValue($x, $y, $value) {
        if (!isset($this->game[$x][$y])) {
            throw new Exception("Position [$x , $y] dose nto exists in this game");
        }
        if ($this->game[$x][$y] != 0) {
            throw new Exception("Value on position [$x , $y] already exists");
        }
        $this->game[$x][$y] = $value;
    }

    /**
     * @param int $x
     * @param int $y
     * @param int $v
     * @return boolean
     */
    public function hasSiblings($x, $y, $v) {
        /**
         * czy w bezposrednim poblizu jest rodzenstwo
         */
        if ($this->getValue($x -1, $y) == $v) {
            return true;
        }
        if ($this->getValue($x +1, $y) == $v) {
            return true;
        }
        if ($this->getValue($x, $y -1) == $v) {
            return true;
        }
        if ($this->getValue($x, $y +1) == $v) {
            return true;
        }
        if ($this->getValue($x -1, $y -1) == $v) {
            return true;
        }
        if ($this->getValue($x +1, $y +1) == $v) {
            return true;
        }
        if ($this->getValue($x -1, $y +1) == $v) {
            return true;
        }
        if ($this->getValue($x +1, $y -1) == $v) {
            return true;
        }

        return false;
    }
    
    /**
     * @param int $v
     * @return boolean
     */
    public function isFirstMoveForValue($v) {
        for ($x = 0; $x < $this->getSize(); $x++) {
            for ($y = 0; $y < $this->getSize(); $y++) {
                $value = $this->getValue($x, $y);
                if ($value == $v) {
                    return false;
                }
            }
        }
        return true;
    }
    
    public function getSize() {
        return count($this->getGame());
    }

}
